package com.ljm.commom.web.filter;

import com.alibaba.fastjson.JSON;
import com.ljm.commom.web.conf.properties.ApiSecurityProperties;
import com.ljm.common.util.Md5Utils;
import com.ljm.common.util.ResultUtil;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 版权：    Copyright by ljm
 * 描述：    对外接口安全校验拦截器
 * 修改人：  HuamingChen
 * 修改时间：2020/3/7
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */
public class ApiSecurityFilter implements Filter {
    private static final Logger logger= LoggerFactory.getLogger(ApiSecurityFilter.class);

    private List<String> outJoinSysUrl;
    private ApiSecurityProperties apiSecurityProperties;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String outJoinSysUrlStr=filterConfig.getInitParameter("outJoinSysUrl");
        if(!StringUtils.isEmpty(outJoinSysUrlStr)){
            outJoinSysUrl=JSON.parseArray(outJoinSysUrlStr,String.class);
        }
        String apiSecurityPropertiesStr=filterConfig.getInitParameter("apiSecurityProperties");
        if(!StringUtils.isEmpty(apiSecurityPropertiesStr)){
            apiSecurityProperties= JSON.parseObject(apiSecurityPropertiesStr,ApiSecurityProperties.class);
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if(!CollectionUtils.isEmpty(outJoinSysUrl)){
            HttpServletRequest request= (HttpServletRequest) servletRequest;
            String context=request.getContextPath();
            String uri=request.getRequestURI();
            String url=uri.replace(context,"");
            if(this.needCheck(outJoinSysUrl,url)){
                String sysId=request.getHeader("sysId");
                String token=request.getHeader("token");
                String secretKey=apiSecurityProperties.getOutJoinSys().get(sysId);
                if(StringUtils.isEmpty(sysId)){
                    this.handResponse(servletResponse,"402","please input sysId in request header");
                }
                if(StringUtils.isEmpty(token)){
                    this.handResponse(servletResponse,"402","please input token in request header");
                }
                if(StringUtils.isEmpty(secretKey)){
                    this.handResponse(servletResponse,"402","sys is not set");
                }
                String data = Md5Utils.hash(IOUtils.readFully(request.getInputStream(),request.getContentLength()));
                String sign = Md5Utils.hash(data+secretKey);
                if(!token.equals(sign)){
                    this.handResponse(servletResponse,"403","Data may have security risks");
                }
            }
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }


    private boolean needCheck(List<String> outJoinSysUrl,String url){
        boolean needCheck =true;
        for(String urlTemp:outJoinSysUrl){
            if(urlTemp.contains("*")?url.contains(urlTemp.replace("*","")):url.equals(urlTemp)){
                needCheck =true;
                break;
            }else{
                needCheck =false;
            }
        }
        return needCheck;
    }

    private void handResponse(ServletResponse servletResponse,String msgCode,String msg){
        try {
            HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
            httpResponse.setContentType("application/json");
            httpResponse.setCharacterEncoding("UTF-8");
            PrintWriter out = httpResponse.getWriter();
            out.println(JSON.toJSONString(ResultUtil.error(msgCode,msg)));
            out.flush();
            out.close();
        } catch (IOException e) {
            logger.error("ApiSecurityFilter handle printwrite error");
        }
    }
}
